import Vue from 'vue'
import VueRouter from 'vue-router'
//引入 Login 组件
import Login from '../components/Login'
//引入Home组件
import Home from'../components/Home'
//引入welcome组件
import Welcome from'../components/Welcome'
//引入Users组件
import Users from "../components/users/Users";

Vue.use(VueRouter)

const routes = [
  //配置路由重定向
  {path: '/', redirect: '/login'},
  //配置路由规则
  { path: '/login', component: Login },
  //配置Home组件
  {path :'/home',
    component: Home,
    redirect: '/welcome',
    children:[
      {path:'/welcome',component:Welcome},
      {path:'/users',component: Users}
    ]
  }
]

const router = new VueRouter({
  routes
})

//配置路由导航守卫
//to代表将要访问的路径
// from代表从哪个路径过来的
//next代表放行next（’login‘）代表强制跳转到/login
router.beforeEach((to,form,next)=>{
  //如果访问的是/login则直接放行
  if(to.path ==='/login') return next()
  //先获取token
  const tokenStr = window.sessionStorage.getItem('token')
  //判断是否有token,如果没有，则强制访问登录页
  if(!tokenStr) return next('/login')
  next()
})

export default router
